package com.gitee.qdbp.jdbc.test.condition;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.gitee.qdbp.jdbc.api.SqlBoot;
import com.gitee.qdbp.jdbc.exception.UnsupportedFieldException;
import com.gitee.qdbp.jdbc.plugins.ColumnNameResolver;
import com.gitee.qdbp.jdbc.plugins.WhereSqlBuilder;
import com.gitee.qdbp.jdbc.sql.SqlBuffer;
import com.gitee.qdbp.jdbc.test.service.EntityTools;
import org.springframework.stereotype.Service;

/**
 * 部门数据权限隔离SqlBuilder<br>
 * 如果不存在部门隔离字段, 那么就查询经办人=当前用户的记录<br>
 * 如果存在部门隔离字段, 那么就查询经办人=当前用户OR部门=指定部门的记录<br>
 *
 * @author zhaohuihua
 * @version 190308
 */
@Service
public class DeptIsolationBuilder implements WhereSqlBuilder<DeptIsolationWhere> {

    @Override
    public Class<DeptIsolationWhere> supported() {
        return DeptIsolationWhere.class;
    }

    @Override
    public SqlBuffer buildSql(DeptIsolationWhere condition, ColumnNameResolver columnResolver, SqlBoot sqlBoot)
            throws UnsupportedFieldException {
        if (condition.isEmpty()) {
            return sqlBoot.newSqlBuffer(); // 没有指定任何隔离字段, 没法加限制条件
        }
        String deptColumn = columnResolver.getColumnName(condition.getDeptField());
        String userColumn = columnResolver.getColumnName(condition.getUserField());
        String agentColumn = columnResolver.getColumnName(condition.getAgentField());

        Map<String, Object> params = new HashMap<>();
        params.put("userColumn", userColumn);
        params.put("agentColumn", agentColumn);
        params.put("deptColumn", deptColumn);
        String userId = EntityTools.getCurrUserIdFromSession();
        List<String> deptIds = EntityTools.getCurrDeptIdsFromSession();
        params.put("specUserIds", Collections.singletonList(userId));
        params.put("specDeptIds", deptIds);

        String sqlId = "GlobalIsolation:deptIsolation";
        return sqlBoot.sqlContainer().generate(sqlId, params);
    }

}
